<template>
	<view>
		<image src="../../../客服微信.jpg"></image>
	</view>
</template>

<script>
import logger from '@/utils/logger';
import messageList from './components/message-list/index';
import messageInput from './components/message-input/index';
import {mapState} from "vuex";
import jwt from '@/utils/jwt.js'
import {isEmpty,isNotEmpty} from '@/utils/utils';
import {chatCheck} from '@/common/http.api.js'
import {timLogin} from '@/utils/tim.js'
const app = getApp();
export default {
	components: {
		messageList,
		messageInput
	},
	props: {},
	data() {
		return {
			chatMode:1,
			firstSendMessage: true,
			bgColor: '#ff5d50',
			conversationName: '',
			conversation: {},
			messageList: [],
			showChat: true,
			goodData:{},
			conversationID: '',
			videoPlay: false,
			videoMessage: {},
			config: {
				sdkAppID: '',
				userID: '',
				userSig: '',
				type: 1,
				tim: null
			}
		};
	},
	created() {
		uni.$on('videoPlayerHandler', value => {
			this.videoPlay = value.isPlay;
			this.videoMessage = value.message;
		});
	},
	watch: {
		isSDKReady: {
			handler(val,oldVal){
				debugger
			  let conversationID = this.conversationID.conversationID;
			  uni.$TUIKit.setMessageRead({
			  	conversationID
			  }).then(() => {
			  	logger.log('TUI-chat | setMessageRead  | ok');
			  });
			  uni.$TUIKit.getConversationProfile(conversationID).then(res => {
			  	debugger
			  	const { conversation } = res.data;
			  	this.conversation = conversation;
			  	this.setData({
			  		conversationName: this.getConversationName(conversation)
			  	});
			  });
			  this.getChatCheck();
			},
			deep: true,
			immediate: false,
		}
	},
	computed: {
		...mapState({
			timLogin: state => state.tim.timLogin,
			isSDKReady: state => state.tim.isSDKReady,
		})
	},
	async onShow() {
		this.locale = this.$i18n.locale;
		console.info("登陆tim")
		await timLogin();
	},
	async onLoad(options) {
		this.chatMode = options.chatMode *1;
		// conversationID: C2C、 GROUP
		logger.log(` TUI-chat | onLoad | conversationID: ${options.conversationID}`);
		this.conversationID = options;
		const { conversationID } = options;
		this.$store.commit("setConversationID", conversationID);
		if(this.isSDKReady){
			
		}
		if(isNotEmpty(options.goodData)){
			this.goodData = JSON.parse(decodeURIComponent(options.goodData));
			//await this.getChatCheck();
		}
	},
	methods: {
		$sendTIMMessage(message) {
			const SDKAppID = getApp().globalData.SDKAppID;
			this.sendMessage({
				detail: {
					message
				}
			});
			uni.$TUIKit.sendMessage(message).then((res) => {
				if(this.firstSendMessage) {
					uni.$aegis.reportEvent({
					    name: 'sendMessage',
					    ext1: 'sendMessage-success',
					    ext2: 'uniTuikitExternal',
					    ext3: `${SDKAppID}`,
					})
				}
				this.firstSendMessage = false
			}).catch((error) => {
				uni.$aegis.reportEvent({
						name: 'sendMessage',
						ext1: `sendMessage-failed#error: ${error}`,
						ext2: 'uniTuikitExternal',
						ext3: `${SDKAppID}`,
			  })
			})
			this.setData({
				displayFlag: ''
			});
		},
		getToAccount() {
			if (!this.conversation || !this.conversation.conversationID) {
				return '';
			}
			switch (this.conversation.type) {
				case 'C2C':
					return this.conversation.conversationID.replace('C2C', '');
				case 'GROUP':
					return this.conversation.conversationID.replace('GROUP', '');
				default:
					return this.conversation.conversationID;
			}
		},
		getChatCheck(){
			let that = this;
			if(this.goodData.id){
				chatCheck({params:{goodId:this.goodData.id,merchantId:this.goodData.merchantId}}).then((res)=>{
					if(res.code === 0 && res.data){
						const message = uni.$TUIKit.createCustomMessage({
							to: this.getToAccount(),
							conversationType: this.conversation.type,
							payload:  {
									// data 字段作为表示，可以自定义
									data: 'good',
									// 获取骰子点数
									extension: JSON.stringify({
										title: that.goodData.name,
										imageUrl: that.goodData.img,
										price: that.goodData.price,
										id:that.goodData.id
									})
							}
						});
						this.$sendTIMMessage(message);
						this.setData({
							displayOrderList: false
						});
					}
				  }).catch(error=>{
					console.error(error)
				  })
			}
		},
		stopVideoHander() {
			this.videoPlay = false;
		},
		getConversationName(conversation) {
			if (conversation.type === '@TIM#SYSTEM') {
				this.setData({
					showChat: false
				});
				return '系统通知';
			}
			if (conversation.type === 'C2C') {
				return conversation.remark || conversation.userProfile.nick || conversation.userProfile.userID;
			}
			if (conversation.type === 'GROUP') {
				return conversation.groupProfile.name || conversation.groupProfile.groupID;
			}
		},
		sendMessage(event) {
			// 将自己发送的消息写进消息列表里面
			this.$refs.messageList.updateMessageList(event.detail.message);
		},
		triggerClose() {
			if (this.showChat) {
				this.$refs.messageInput.handleClose();
			}
		},
		goBack() {
			const pages = getCurrentPages(); // 当前页面栈
			if (
				pages[pages.length - 2].route === 'pages/TUI-Conversation/create-conversation/create' ||
				pages[pages.length - 2].route === 'pages/TUI-Group/create-group/create' ||
				pages[pages.length - 2].route === 'pages/TUI-Group/join-group/join'
			) {
				uni.navigateBack({
					delta: 2
				});
			} else {
				uni.navigateBack({
					delta: 1
				});
			}
			uni.$TUIKit
				.setMessageRead({
					conversationID: this.conversationID
				})
				.then(() => {});
		}
	}
};
</script>
<style>
.container {
	width: 100vw;
	height: 100vh;
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	display: flex;
	flex-direction: column;
}

.tui-chatroom-navigatorbar {
	position: relative;
	/*top: 0;*/
	flex-shrink: 0;
	width: 750rpx;
	height: 176rpx;
	background-color: #006EFF;
}

.tui-chatroom-navigatorbar-back {
	position: absolute;
	width: 48rpx;
	height: 48rpx;
	left: 24rpx;
	bottom: 20rpx;
}

.conversation-title {
	position: absolute;
	width: 350rpx;
	height: 88rpx;
	line-height: 56rpx;
	font-size: 36rpx;
	color: #FFFFFF;
	z-index: 100;
	bottom: 0;
	left: 200rpx;
	display: flex;
	justify-content: center;
	align-items: center;
}

.message-list {
	margin-top: 50px;
	flex: 1;
	width: 100vw;
	overflow-y: scroll;
}

.message-input {
	flex-shrink: 0;
	width: 100%;
}

.calling {
	position: fixed;
	z-index: 199;
	top: 0;
	/*  #ifdef  H5  */
	top: calc(88rpx + constant(safe-area-inset-top));
	top: calc(88rpx + env(safe-area-inset-top));
	/*  #endif  */
	bottom: 0;
	right: 0;
}

.group-profile {
	top: 176rpx;
	left: 0;
	z-index: 1111
}

.container-box {
	position: fixed;
	display: flex;
	justify-content: center;
	align-items: center;
	left: 0;
	right: 0;
	bottom: 0;
	top: 0;
	background-color: rgba(0, 0, 0, 0.5);
}

.video-message {
	width: 90vw;
	height: 300px;
}

</style>
